import 'dart:math';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/word.dart';
import '../models/learning_record.dart';
import '../models/wrong_question.dart';
import '../services/storage_service.dart';
import 'word_provider.dart';
import '../../data/master_vocabulary.dart';

// 单词学习题目类
class VocabularyQuestion {
  final Word correctWord;
  final List<String> options;
  final int correctIndex;

  VocabularyQuestion({
    required this.correctWord,
    required this.options,
    required this.correctIndex,
  });
}

// 学习会话状态
class VocabularyLearningState {
  final List<VocabularyQuestion> questions;
  final int currentQuestionIndex;
  final List<bool> userAnswers;
  final List<int> selectedAnswers;
  final bool isCompleted;
  final int totalCorrect;
  final Set<String> masteredWords;
  final DateTime startTime;

  VocabularyLearningState({
    required this.questions,
    this.currentQuestionIndex = 0,
    required this.userAnswers,
    required this.selectedAnswers,
    this.isCompleted = false,
    this.totalCorrect = 0,
    required this.masteredWords,
    required this.startTime,
  });

  VocabularyQuestion? get currentQuestion {
    if (currentQuestionIndex < questions.length) {
      return questions[currentQuestionIndex];
    }
    return null;
  }

  bool get hasNext => currentQuestionIndex < questions.length - 1;
  bool get hasPrevious => currentQuestionIndex > 0;

  double get progress => 
      questions.isEmpty ? 0.0 : (currentQuestionIndex + 1) / questions.length;

  double get accuracy => 
      userAnswers.isEmpty ? 0.0 : totalCorrect / userAnswers.length;

  VocabularyLearningState copyWith({
    List<VocabularyQuestion>? questions,
    int? currentQuestionIndex,
    List<bool>? userAnswers,
    List<int>? selectedAnswers,
    bool? isCompleted,
    int? totalCorrect,
    Set<String>? masteredWords,
    DateTime? startTime,
  }) {
    return VocabularyLearningState(
      questions: questions ?? this.questions,
      currentQuestionIndex: currentQuestionIndex ?? this.currentQuestionIndex,
      userAnswers: userAnswers ?? this.userAnswers,
      selectedAnswers: selectedAnswers ?? this.selectedAnswers,
      isCompleted: isCompleted ?? this.isCompleted,
      totalCorrect: totalCorrect ?? this.totalCorrect,
      masteredWords: masteredWords ?? this.masteredWords,
      startTime: startTime ?? this.startTime,
    );
  }
}

// 学习状态管理器
class VocabularyLearningNotifier extends StateNotifier<VocabularyLearningState> {
  final StorageService _storageService;
  final Ref _ref;

  VocabularyLearningNotifier(this._storageService, this._ref) : super(
    VocabularyLearningState(
      questions: [],
      userAnswers: [],
      selectedAnswers: [],
      masteredWords: <String>{},
      startTime: DateTime.now(),
    ),
  ) {
    _loadMasteredWords();
  }

  // 加载已掌握的词汇
  Future<void> _loadMasteredWords() async {
    final masteredWords = await _storageService.getMasteredWords();
    state = state.copyWith(masteredWords: masteredWords);
  }

  // 初始化学习会话
  Future<void> initializeLearning({String? category, int? difficulty, int questionCount = 20}) async {
    // 确保已掌握词汇已加载
    await _loadMasteredWords();
    
    List<Word> wordPool;
    
    if (category != null) {
      wordPool = MasterVocabulary.getWordsByCategory(category);
    } else if (difficulty != null) {
      wordPool = MasterVocabulary.getWordsByDifficulty(difficulty);
    } else {
      wordPool = MasterVocabulary.allVocabulary;
    }

    // 获取当前学习索引
    final currentIndex = await _storageService.getCurrentLearningIndex();
    
    // 筛选出未掌握的单词，从当前索引开始
    final unmastered = wordPool.where((word) => 
        !state.masteredWords.contains(word.id)).toList();
    
    List<Word> selectedWords;
    if (unmastered.isEmpty) {
      // 如果所有单词都已掌握，重新开始
      selectedWords = wordPool.take(questionCount).toList();
      await _storageService.saveCurrentLearningIndex(0);
    } else {
      // 从当前索引开始选择词汇
      final startIndex = currentIndex % unmastered.length;
      final endIndex = (startIndex + questionCount).clamp(0, unmastered.length);
      
      if (endIndex <= unmastered.length) {
        selectedWords = unmastered.sublist(startIndex, endIndex);
      } else {
        // 如果不够，从头开始补充
        selectedWords = [
          ...unmastered.sublist(startIndex),
          ...unmastered.sublist(0, questionCount - (unmastered.length - startIndex)),
        ];
      }
    }

    final questions = selectedWords.map((word) => _generateQuestion(word)).toList();

    state = VocabularyLearningState(
      questions: questions,
      userAnswers: List.filled(questions.length, false),
      selectedAnswers: List.filled(questions.length, -1),
      masteredWords: Set.from(state.masteredWords),
      startTime: DateTime.now(),
    );
  }

  // 生成四选一题目
  VocabularyQuestion _generateQuestion(Word correctWord) {
    final allWords = MasterVocabulary.allVocabulary;
    final random = Random();
    
    // 获取3个错误选项
    final wrongWords = allWords.where((word) => 
        word.id != correctWord.id && 
        word.category == correctWord.category).toList();
    
    if (wrongWords.length < 3) {
      // 如果同类别词汇不足，从其他类别选择
      wrongWords.addAll(allWords.where((word) => 
          word.id != correctWord.id).toList());
    }
    
    wrongWords.shuffle(random);
    final selectedWrong = wrongWords.take(3).toList();
    
    // 创建选项列表
    final options = <String>[
      correctWord.english,
      ...selectedWrong.map((word) => word.english),
    ];
    
    // 随机排列选项
    options.shuffle(random);
    final correctIndex = options.indexOf(correctWord.english);
    
    return VocabularyQuestion(
      correctWord: correctWord,
      options: options,
      correctIndex: correctIndex,
    );
  }

  // 回答问题
  Future<void> answerQuestion(int selectedIndex) async {
    if (state.currentQuestion == null) return;
    
    final isCorrect = selectedIndex == state.currentQuestion!.correctIndex;
    final newUserAnswers = List<bool>.from(state.userAnswers);
    final newSelectedAnswers = List<int>.from(state.selectedAnswers);
    
    newUserAnswers[state.currentQuestionIndex] = isCorrect;
    newSelectedAnswers[state.currentQuestionIndex] = selectedIndex;
    
    final newTotalCorrect = isCorrect 
        ? state.totalCorrect + 1 
        : state.totalCorrect;
    
    final newMasteredWords = Set<String>.from(state.masteredWords);
    if (isCorrect) {
      newMasteredWords.add(state.currentQuestion!.correctWord.id);
      // 立即保存已掌握的词汇
      await _storageService.addMasteredWord(state.currentQuestion!.correctWord.id);
    } else {
      // 答错了，检查错题本中是否已存在，如果不存在则添加
      final currentQuestion = state.currentQuestion!;
      final wrongQuestion = WrongQuestion(
        id: '${DateTime.now().millisecondsSinceEpoch}_${currentQuestion.correctWord.id}',
        wordId: currentQuestion.correctWord.id,
        question: 'What is the English translation of "${currentQuestion.correctWord.esperanto}"?',
        options: currentQuestion.options,
        correctIndex: currentQuestion.correctIndex,
        selectedIndex: selectedIndex,
        wrongAt: DateTime.now(),
      );
      
      await _storageService.addWrongQuestion(wrongQuestion);
      print('Added wrong question: ${currentQuestion.correctWord.esperanto} to wrong questions book');
    }

    // 立即保存学习记录
    final record = LearningRecord(
      id: '${DateTime.now().millisecondsSinceEpoch}_${state.currentQuestionIndex}',
      wordId: state.currentQuestion!.correctWord.id,
      studiedAt: DateTime.now(),
      isCorrect: isCorrect,
      difficulty: state.currentQuestion!.correctWord.difficulty.toString(),
    );
    
    await _storageService.addLearningRecord(record);

    // 调试输出
    print('Answer recorded: ${state.currentQuestion!.correctWord.esperanto} - $isCorrect');
    await _storageService.debugPrintStoredData();

    // 触发刷新
    _ref.read(refreshTriggerProvider.notifier).state++;

    state = state.copyWith(
      userAnswers: newUserAnswers,
      selectedAnswers: newSelectedAnswers,
      totalCorrect: newTotalCorrect,
      masteredWords: newMasteredWords,
    );
  }

  // 下一题
  Future<void> nextQuestion() async {
    if (state.hasNext) {
      state = state.copyWith(
        currentQuestionIndex: state.currentQuestionIndex + 1,
      );
    } else {
      // 完成学习，更新学习索引
      await _completeLearning();
      state = state.copyWith(isCompleted: true);
    }
  }

  // 完成学习会话
  Future<void> _completeLearning() async {
    // 更新学习索引
    final currentIndex = await _storageService.getCurrentLearningIndex();
    final newIndex = currentIndex + state.questions.length;
    await _storageService.saveCurrentLearningIndex(newIndex);
    
    // 保存已掌握词汇到存储
    await _storageService.saveMasteredWords(state.masteredWords);
    
    // 清除学习会话状态
    await _storageService.clearLearningSessionState();
    
    // 触发最终刷新
    _ref.read(refreshTriggerProvider.notifier).state++;
  }

  // 上一题
  void previousQuestion() {
    if (state.hasPrevious) {
      state = state.copyWith(
        currentQuestionIndex: state.currentQuestionIndex - 1,
      );
    }
  }

  // 重新开始
  Future<void> restartLearning() async {
    // 重新加载已掌握的词汇
    await _loadMasteredWords();
    
    state = VocabularyLearningState(
      questions: [],
      userAnswers: [],
      selectedAnswers: [],
      masteredWords: state.masteredWords, // 保留已掌握的单词
      startTime: DateTime.now(),
    );
  }

  // 获取学习统计
  Map<String, dynamic> getLearningStats() {
    final duration = DateTime.now().difference(state.startTime);
    return {
      'totalQuestions': state.questions.length,
      'answeredQuestions': state.userAnswers.where((answer) => answer != null).length,
      'correctAnswers': state.totalCorrect,
      'accuracy': state.accuracy,
      'masteredWords': state.masteredWords.length,
      'duration': duration,
      'questionsPerMinute': state.questions.isNotEmpty 
          ? (state.currentQuestionIndex + 1) / (duration.inSeconds / 60.0)
          : 0.0,
    };
  }
}

// Provider
final vocabularyLearningProvider = 
    StateNotifierProvider<VocabularyLearningNotifier, VocabularyLearningState>(
  (ref) => VocabularyLearningNotifier(ref.read(storageServiceProvider), ref),
);

// 掌握单词数量Provider
final masteredWordsCountProvider = Provider<int>((ref) {
  final learningState = ref.watch(vocabularyLearningProvider);
  return learningState.masteredWords.length;
});

// 学习进度Provider
final learningProgressProvider = Provider<double>((ref) {
  final learningState = ref.watch(vocabularyLearningProvider);
  return learningState.progress;
});

// 从存储加载已掌握词汇数量的Provider
final storedMasteredWordsCountProvider = FutureProvider<int>((ref) async {
  final storageService = ref.watch(storageServiceProvider);
  final masteredWords = await storageService.getMasteredWords();
  return masteredWords.length;
});

// 学习统计Provider - 添加依赖刷新
final learningStatsProvider = FutureProvider<Map<String, dynamic>>((ref) async {
  final storageService = ref.watch(storageServiceProvider);
  
  // 监听词汇学习状态变化，当状态变化时重新计算
  final learningState = ref.watch(vocabularyLearningProvider);
  
  final masteredWords = await storageService.getMasteredWords();
  final currentIndex = await storageService.getCurrentLearningIndex();
  final totalWords = MasterVocabulary.totalWordCount;
  
  return {
    'masteredCount': masteredWords.length,
    'totalCount': totalWords,
    'progress': masteredWords.length / totalWords,
    'currentIndex': currentIndex,
    'sessionMastered': learningState.masteredWords.length, // 添加会话中掌握的数量
  };
});

// 添加一个简单的刷新触发器
final refreshTriggerProvider = StateProvider<int>((ref) => 0);

// 学习记录刷新Provider
final refreshableRecordsProvider = FutureProvider<List<LearningRecord>>((ref) async {
  final storageService = ref.watch(storageServiceProvider);
  // 监听刷新触发器
  ref.watch(refreshTriggerProvider);
  return storageService.getLearningRecords();
}); 